package net.xdclass.util;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;

/**
 * @author Administrator
 * @description 支付工具
 * @since 2023-08-22 23:21
 */
@Component
@Slf4j
public class PayUtil {

    @Autowired
    private RestTemplate restTemplate;

    public Boolean payUtil(HttpResponse response) throws IOException {
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != 200) {
            log.error("订单生成失败");
            return false;
        }
        String body = EntityUtils.toString(response.getEntity(), "UTF-8");
        JSONObject orderResultObj = JSONObject.parseObject(body);
        if (((int) orderResultObj.get("code")) != 0) {
            log.error("订单生成失败");
            return false;
        }
        String payUrl = orderResultObj.getJSONObject("data").getString("pay_url");
        ResponseEntity<JsonData> payResponse = restTemplate.getForEntity(payUrl, JsonData.class);
        HttpStatus payStatus = payResponse.getStatusCode();
        if (payStatus.value() != 200) {
            log.error("支付失败");
            return false;
        }
        JsonData resultData = payResponse.getBody();
        if (resultData.getCode() == 0) {
            log.info("订单支付成功");
            return true;
        }
        log.info("订单支付失败");
        return false;
    }

}
